package cn.yjh.utils;

import java.nio.ByteBuffer;

/**
 * @DESC:
 * @AUTHOR: YouJinhua
 * @DATE: 2021-12-14 21:53:33
 * @VERSION: 1.0
 */
public class ByteBufferUtil {

    private ByteBufferUtil () {}

    /**
     * 将两个 bytebuffer 合并
     *
     * @param byteBuffer1
     * @param byteBuffer2
     * @return
     */
    public static ByteBuffer composite(ByteBuffer byteBuffer1, ByteBuffer byteBuffer2) {
        int capacity = byteBuffer1.limit() - byteBuffer1.position() + byteBuffer2.limit() - byteBuffer2.position();
        ByteBuffer ret = ByteBuffer.allocate(capacity);

        ret.put(byteBuffer1);
        ret.put(byteBuffer2);

        ret.position(0);
        ret.limit(ret.capacity());
        return ret;
    }

    /**
     * 获取 bytebuffer 中可读的内容
     *
     * @param byteBuffer
     * @param size
     * @return
     */
    public static byte[] readBuffer(ByteBuffer byteBuffer, int size) {
        byte[] bytes = new byte[size];

        byteBuffer.get(bytes);

        return bytes;
    }
}
